package ru.nsu.fit.iconveyor.conveyor.utils.file;

import java.io.*;
import java.net.URL;

/**
 * This static class copies src file to dst file.
 *
 * @author Timur Zolotuhin (tzolotuhin@gmail.com)
 */
public class CopyFile {
	public static void copyFile(String srcFile, String dstFile) throws Exception {
		InputStream in = null;
		OutputStream out = null;
		try {
			File f1 = new File(srcFile);
			File f2 = new File(dstFile);
			in = new FileInputStream(f1);
			out = new FileOutputStream(f2);

			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
		} finally {
			if (in != null) {
                in.close();
			}
			if (out != null) {
                out.close();
			}
		}
	}

    public static void copyString2File(String text, String fileName, String directoryPath) throws Exception {
        File dstDir = new File(directoryPath);

        if (!dstDir.exists() && !dstDir.mkdirs()) {
             throw new FileNotFoundException("Can't create directory = " + dstDir);
        }

        OutputStream out = null;
        try {
            File f2 = new File(dstDir.getAbsolutePath() + File.separator + fileName);
            out = new FileOutputStream(f2);

            byte[] bytes = text.getBytes();
            out.write(bytes, 0, bytes.length);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    public static void copyFile2Directory(URL srcFileName, String dstFileName, String directoryPath) throws Exception {
        File dstDir = new File(directoryPath);

        if (!dstDir.exists() && !dstDir.mkdirs()) {
            throw new FileNotFoundException("Can't create directory = " + dstDir);
        }

        InputStream in = null;
        OutputStream out = null;
        try {
            File f1 = new File(srcFileName.toURI());
            File f2 = new File(dstDir.getAbsolutePath() + File.separator + dstFileName);
            in = new FileInputStream(f1);
            out = new FileOutputStream(f2);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}
